// let gulp = require('gulp'),
//     ts = require('gulp-typescript');

// let tsProject = ts.createProject('tsconfig.json');

// gulp.task( "default", () => {
//     return tsProject.src()
//         .pipe( tsProject())
//         .js
//         .pipe( gulp.dest( 'dist'));
// });

let gulp = require('gulp'),
    browserify = require('browserify'),
    source = require('vinyl-source-stream'),
    watchify = require("watchify"),
    tsify = require('tsify'),
    uglify = require('gulp-uglify');
    sourcemaps = require('gulp-sourcemaps');
    buffer = require('vinyl-buffer');
    gutil = require("gulp-util"),
    opn = require('opn');

let paths = {
    pages: [
        'src/*.html'
    ]
};

let watchedBrowserify = watchify(
    browserify({
        basedir: '.',
        debug: true,
        entries: [
            'src/main.ts'
        ],
        cache: {},
        packageCache: {}
    })
    .plugin( tsify)
);

gulp.task( 'copy html', () => {
    return gulp.src( paths.pages)
        .pipe( gulp.dest("dist"));
});

let bundle = () => {
    return watchedBrowserify
        .transform('babelify', {
            presets: ['es2015'],
            extensions: ['.ts']
        })
        .bundle()
        .pipe( source('bundle.js'))
        .pipe( buffer())
        .pipe( sourcemaps.init({loadMaps: true}))
        .pipe( uglify())
        .pipe( sourcemaps.write('./'))
        .pipe( gulp.dest('dist'));
}

gulp.task( "default", [ 'copy html'], async () => {
    await bundle();
    opn( 'dist/index.html');
});

watchedBrowserify.on("update", bundle);
watchedBrowserify.on("log", gutil.log);